package com.bbx.taxi.client.Activity.Menu;
import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.passanger.Return.Version;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.DB.AddressDB;
import com.bbx.taxi.client.DB.ContactsDB;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Guide.GuideActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity;
import com.bbx.taxi.client.Activity.login.WelcomeActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.ClauseMsg;
import com.bbx.taxi.client.Bean.Extra.GuideMsg;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Service.UpgradeService;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck;
import com.bbx.taxi.client.UpdateChecker.UpdateCheck.OnUpdateListener;
import com.bbx.taxi.client.UpdateChecker.baidu.MyCPCheckUpdateCallback;
import com.bbx.taxi.client.UpdateChecker.qihoo.MyQihooUpdate;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad;
import com.bbx.taxi.client.UpdateChecker.ui.MyUpdateLoad.UpdateType;
import com.bbx.taxi.client.Util.AppStarted;
import com.bbx.taxi.client.Util.ChannelName;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickLeftListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickRightListener;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;

public class SetActivity extends BaseBBXActivity implements OnUpdateListener{
	@Bind(R.id.btn_quit)
	Button btn_quit;
	@Bind(R.id.btn_update)
	Button btn_update;
	@Bind(R.id.btn_clear)
	Button btn_clear;
	@Bind(R.id.btn_share)
	Button btn_share;
	@Bind(R.id.btn_help)
	Button btn_help;
	@Bind(R.id.btn_about)
	Button btn_about;
	@Bind(R.id.btn_clause)
	Button btn_clause;
	@Bind(R.id.btn_version)
	Button btn_version;
	@Bind(R.id.tv_version)
	TextView tv_version;
	@Bind(R.id.pop_background)
	View pop_background;
	UpdateCheck mUpdateCheck;
    private static final String ATTR_PACKAGE_STATS="PackageStats";
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		setContentView(R.layout.set);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {

		setTitle(getString(R.string.set_title));
		btn_quit.setOnClickListener(this);
		btn_update.setOnClickListener(this);
		btn_clear.setOnClickListener(this);
		btn_share.setOnClickListener(this);
		btn_help.setOnClickListener(this);
		btn_about.setOnClickListener(this);
		btn_clause.setOnClickListener(this);
	}

	@Override
	protected void initData() {

	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
	
		switch (v.getId()) {
		case R.id.btn_quit:
			final MyAlertDailog dialog=new MyAlertDailog(this);
			dialog.setTitle(getString(R.string.mydailog_title));
			dialog.setContent(getString(R.string.mydailog_content_exit));
			dialog.setLeftButtonText(getString(R.string.mydailog_cancel));
			dialog.setRightButtonText(getString(R.string.mydailog_confirm));
			if (dialog != null && !dialog.isShowing()) {
				dialog.show();
			}
			dialog.setOnClickLeftListener(new onClickLeftListener() {	
				@Override
				public void onClickLeft() {
					dialog.dismiss();
				}
			});
			dialog.setOnClickRightListener(new onClickRightListener() {
				
				@Override
				public void onClickRight() {
					dialog.dismiss();
					Intent intent = new Intent(SetActivity.this, LoginActivity.class);
					startActivity(intent);

				}
			});

			break;
		case R.id.btn_update:
			switch(Value.isMode){
			case Value.isNormal:
				mUpdateCheck=UpdateCheck.getInstance(this);
				mUpdateCheck.setOnUpdateListener(this,WelcomeActivity.platform,ChannelName.getAppMetaData(this));	
				break;
			case Value.isBaidu:
				//百度更新UpdateType
				BDAutoUpdateSDK.cpUpdateCheck(this, new MyCPCheckUpdateCallback(context,loaddialog,UpdateType.TYPE_SET));		
				break;
			case Value.is360:
				new MyQihooUpdate(context,null,UpdateType.TYPE_SET).onStart();
				break;
			}
			
			break;
		case R.id.btn_clear:
	             mHandler.sendEmptyMessage(1);
			break;
		case R.id.btn_help:
			startActivity(new Intent(this,ClauseActivity.class).putExtra(ClauseMsg.extra_clause, ClauseMsg.CLAUSE_HELP));
			break;
		case R.id.btn_about:
			startActivity(new Intent(this,AboutActivity.class));
			break;
		case R.id.btn_clause:
			startActivity(new Intent(this,ClauseActivity.class).putExtra(ClauseMsg.extra_clause, ClauseMsg.CLAUSE_SERVICE));
			break;
		}
		super.onClick(v);
	}
	 private Handler mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					final MyAlertDailog dialog=new MyAlertDailog(context);
						dialog.setTitle(getString(R.string.mydailog_title));
						dialog.setContent(String.format(getString(R.string.mydailog_content_cache), getTotalCacheSize(SetActivity.this)));
						dialog.setLeftButtonText(getString(R.string.mydailog_cancel));
						dialog.setRightButtonText(getString(R.string.mydailog_confirm));
						if (dialog != null && !dialog.isShowing()) {
							dialog.show();
						}
						dialog.setOnClickLeftListener(new onClickLeftListener() {	
							@Override
							public void onClickLeft() {
								dialog.dismiss();
							}
						});
						dialog.setOnClickRightListener(new onClickRightListener() {
							
							@Override
							public void onClickRight() {
								DataCleanManager.clearAllCache(SetActivity.this);
								new AddressDB().onDelete();
						    	new ContactsDB().onDelete();
						    	SharedPreUtil.putBooleanValue(SetActivity.this,
										SharedPreEncryptUtil.isMarkOnlineDialog,true);
								dialog.dismiss();
								ToastUtil.showToast(context,R.string.clear_success);
							}
						});
					break;
				default:
					break;
				}
			}
			};
	/**
	 * 获取文件大小
	 * 
	 * @param length
	 * @return
	 */
	 public static String getTotalCacheSize(Context context)  {
         long cacheSize = 0;
		try {
			cacheSize = getFolderSize(context.getCacheDir());
         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
             cacheSize += getFolderSize(context.getExternalCacheDir());
         }  

		} catch (Exception e) {
			e.printStackTrace();
		}
         return getFormatSize(cacheSize);
     }
	 // 获取文件  
	    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据  
	    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据  
	    public static long getFolderSize(File file) throws Exception {  
	        long size = 0;  
	        try {  
	            File[] fileList = file.listFiles();  
	            for (int i = 0; i < fileList.length; i++) {  
	                // 如果下面还有文件  
	                if (fileList[i].isDirectory()) {  
	                    size = size + getFolderSize(fileList[i]);  
	                } else {  
	                    size = size + fileList[i].length();  
	                }  
	            }  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return size;  
	    }  
	    
	    /** 
	     * 格式化单位 
	     *  
	     * @param size 
	     * @return 
	     */ 
	    public static String getFormatSize(double size) {  
	        double kiloByte = size / 1024;  
	        if (kiloByte < 1) {  
//	            return size + "Byte";  
	            return "0K";
	        }  
	   
	        double megaByte = kiloByte / 1024;  
	        if (megaByte < 1) {  
	            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));  
	            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)  
	                    .toPlainString() + "KB";  
	        }  
	   
	        double gigaByte = megaByte / 1024;  
	        if (gigaByte < 1) {  
	            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));  
	            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)  
	                    .toPlainString() + "MB";  
	        }  
	   
	        double teraBytes = gigaByte / 1024;  
	        if (teraBytes < 1) {  
	            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));  
	            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)  
	                    .toPlainString() + "GB";  
	        }  
	        BigDecimal result4 = new BigDecimal(teraBytes);  
	        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()  
	                + "TB";  
	    }

		@Override
		public void onUpdateSuccess(Version version) {
		
			if(version.getforce_update()==1){//强制更新
				onShowForceUpdate(version);
			}
			else{
				onShowNoForceUpdate(version);
			}
			
		}

		@Override
		public void onUpdateFailed(int status,String msg) {
			if(msg==null||status==-1){
				onshowNoUpdate();
			}
			else{
				ToastUtil.showToast(context, getResources().getString(R.string.no_network));
			}
		}  
		/**
		 * 已经是最新版本了
		 */
		public void onshowNoUpdate(){
			final MyAlertDailog dialog=new MyAlertDailog(this);
			dialog.setTitle(getString(R.string.mydailog_title));
			dialog.setContent(getString(R.string.mydailog_update_latest));
			dialog.setSingle(getString(R.string.mydailog_confirm));
			dialog.show();
			dialog.setOnClickSingleListener(new onClickSingleListener() {
				@Override
				public void onClickSingle() {
					dialog.dismiss();
				}
			});
		}
		/**
		 * 强制更新
		 */
		public void onShowForceUpdate(final Version version){
			final MyAlertDailog dialog=new MyAlertDailog(this);
			String updatecontent="";
			try{updatecontent=version.getDescription().replace("<br>", "\n");}catch(Exception e){}
			if(updatecontent!=null&&updatecontent.contains("\n")){
				dialog.setContent2Gravity(Gravity.LEFT);
			}
			dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content2));
			dialog.setContent2(updatecontent);
			dialog.setSingle(this.getResources().getString(R.string.mydailog_confirm_update));
			dialog.show();
			dialog.setOnClickSingleListener(new onClickSingleListener() {
				@Override
				public void onClickSingle() {
					dialog.dismiss();
//					mUpdateCheck.downloadApk(url, pathSavedDir);
					onUpdate(true,version);
				}
			});
		}
	    /**
	     * 弹出不强制更新
	     */
	    public void onShowNoForceUpdate(final Version version){
	    	final MyAlertDailog dialog=new MyAlertDailog(this);
	    	String updatecontent="";
			try{updatecontent=version.getDescription().replace("<br>", "\n");}catch(Exception e){}
			if(updatecontent!=null&&updatecontent.contains("\n")){
				dialog.setContent2Gravity(Gravity.LEFT);
			}
	    	dialog.setTitle(this.getResources().getString(R.string.mydailog_update_content2));
			dialog.setContent2(updatecontent);
			dialog.setLeftButtonText(this.getResources().getString(R.string.mydailog_cancel_update));
			dialog.setRightButtonText(this.getResources().getString(R.string.mydailog_confirm_update));
			if (dialog != null && !dialog.isShowing()) {
				dialog.show();
			}
			dialog.setOnClickLeftListener(new onClickLeftListener() {	
				@Override
				public void onClickLeft() {
					dialog.dismiss();
				}
			});
			dialog.setOnClickRightListener(new onClickRightListener() {
				
				@Override
				public void onClickRight() {
					dialog.dismiss();
//					mUpdateCheck.downloadApk(url, pathSavedDir); 
					onUpdate(false,version);
				}
			});
	    }
	    /** 
	     * 更新
	     * @param isForce 是否强制更新
	     * @param url
	     */ 	
	    public void onUpdate(boolean isForce,Version version){
	    	MyUpdateLoad mMyUpdateLoad=new MyUpdateLoad();
			mMyUpdateLoad.downloadApk(context, isForce,UpdateType.TYPE_SET,version.getURL(),version.getVersion());
			ToastUtil.showToast(this,R.string.downloading);
			if (isForce) {
				 android.os.Process.killProcess(android.os.Process.myPid());
				context.stopService(new Intent(context, LoginService.class));
			} else {

			}
	    }
}
